#include "pch.h"
#include "ReflectionEffect.h"
#include "RendererEngine.h"
#include "LightActor.h"

namespace mini
{
	CReflectionEffect::CReflectionEffect()
	{
		mType = EntityType::RenderViewPort;
	}

	CReflectionEffect::~CReflectionEffect()
	{
	}

	void CReflectionEffect::buildRefCamera(const CPoint3F& eye, const CPoint3F& lookat)
	{
		setName("ReflectionViewport");
		initViewPortSize(GEngine->getDeviceWidth(), GEngine->getDeviceHeight());
		setRendererFlag(RendererType::FrontRenderer);
		createBuildCamera("ReflectionCamera", eye, lookat);
		auto pScene = GEngine->getCurrentScene();
		for (auto item : pScene->getRenderNodes())
		{
			auto renderNode = item->Clone();
			renderNode->setMaterialUnit(mpMaterialUnit);
			addRenderNode(renderNode);
		}
		pScene->addActor(this);
		if (mpMaterialUnit != nullptr)
		{
			auto pShader = mpMaterialUnit->getShaderUnit(0)->getShader();
			if (nullptr != pShader)
			{
				//{
				//	LightDrawCell* pCell = CDrawCellManager::getSinglePtr()->getDrawCell<LightDrawCell>();
				//	if (nullptr != pCell)
				//	{
				//		pCell->pShader = pShader;
				//		CActor* pActor = GEngine->getCurrentScene()->findActorByName("Sun");
				//		if (nullptr != pActor)
				//		{
				//			pCell->pActor = (pActor);
				//		}
				//	}
				//}
				//{
				//	ReflectionDrawCell* pCell = CDrawCellManager::getSinglePtr()->getDrawCell<ReflectionDrawCell>();
				//	if (nullptr != pCell)
				//	{
				//		pCell->pShader = pShader;
				//		pCell->pActor = mpCamera;
				//	}
				//}
			}
		}
	}

	void CReflectionEffect::buildRenderViewport()
	{
		auto pScene = GEngine->getCurrentScene();
		for (auto item : pScene->getRenderNodes())
		{
			addRenderNode(item);
		}
		pScene->addActor(this);
	}

	void CReflectionEffect::updateFrame(float fDeltaTime)
	{
		if (nullptr != mpMaterialUnit)
		{
			auto matrix = mpCamera->getViewMatrix();
			CMatrix refMx;
			D3DXMatrixTranspose(&refMx, &matrix);
			mpMaterialUnit->updateVSConstBuffer(5, &refMx);
		}
		else
		{
			if (0 != mpMeshUnits.size())
			{
				auto materialUnit = mpMeshUnits.front()->getMaterialUnit();
				auto matrix = mpCamera->getViewMatrix();
				CMatrix refMx;
				D3DXMatrixTranspose(&refMx, &matrix);
				materialUnit->updateVSConstBuffer(5, &refMx);
			}
		}
	}
}